/**
 * All rights Reserved, Designed By OprCalf
 * Copyright:    Copyright(C) 2016-2020
 * Company       LengYin Ltd.
 */

package com.platform.gateway.common.filter;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;

/**
 * @projectName:  platform-gateway-demo
 * @package:      com.platform.gateway.common.filters
 * @className:    ErrorFilter.java
 * @description:  全局异常
 * @author:       OprCalf
 * @date:         2020年3月5日
 */
@Slf4j
@Component
public class ErrorFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return Integer.MIN_VALUE;
    }

    @Override
    public boolean shouldFilter() {
        final RequestContext ctx = RequestContext.getCurrentContext();
        if (ctx.getThrowable() != null) {
            log.error("{}", ctx.getThrowable().fillInStackTrace());
            if (ctx.sendZuulResponse()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public Object run() {
        try {
            final RequestContext ctx = RequestContext.getCurrentContext();
            final HttpServletRequest request = ctx.getRequest();
            final RequestDispatcher dispatcher = request.getRequestDispatcher("/gobleError");
            if (dispatcher != null) {
                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(HttpStatus.BAD_GATEWAY.value());
                ctx.getResponse().setContentType("application/json;charset=UTF-8");
                dispatcher.forward(request, ctx.getResponse());
            }
        }
        catch (final Exception ex) {
            ReflectionUtils.rethrowRuntimeException(ex);
        }
        return null;
    }

}
